07. Exercise: Builder
Building a Builder
Remember that "bean" class, UdacisearchClient, you worked with in previous exercises? That class has a constructor with lots of parameters. Furthermore, it's a mutable class. It's the perfect candidate for the Builder Pattern.
This should be a fairly straightforward procedure — you are going to take the UdacisearchClient class and make a Builder class for it. This will provide the following benefits:
UdacisearchClientwill become an immuable type, which means its value does not change after it is created.- The builder class will emulate named parameters. Unlike the large constructor, the builder makes it harder for callers to accidentally mix up the order of the client properties.
Here's how to apply the builder pattern:
- First, make the
UdacisearchClientconstructorprivateinstead ofpublic. - Next, make all the instance fields
finaland remove all the setter methods, such asUdacisearchClient#setId(int). Congratulations,UdacisearchClientis now an immutable type — but it's no good if we can't instantiate it! Don't forget to delete the default values of the fields. - Give
UdacisearchClienta static inner class calledBuilder. Give the builder class a non-finalinstance field corresponding to each field ofUdacisearchClient. - Create setter methods for all the builder's fields. Each method should return a reference to the
Builderitself (i.e.,this). - Finally, add a
UdacisearchClient.Builder#build()method that calls the now-privateUdacisearchClientconstructor. - Try out
UdacisearchClient.BuilderinMain.javaby constructing theclientvariable with the newBuilderclass:javac Main.java java Main
What do you think? Is the Builder easier to work with than the old UdacisearchClient constructor?
TODO List
Task Feedback:
Nice work!
Code
If you need a code on the https://github.com/udacity.
export PATH=/data/jdk-15.0.1/bin:$PATH
export JAVA_HOME=/data/jdk-15.0.1/bin